Java syntax
part 26/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
The access modifiers, or inheritance modifiers, set the accessibility of classes, methods, and other members. Members marked as public can be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed.
public class Foo {
int go() {
return 0;
}
private class Bar {
}
}
The following table shows whether code within a class has access to the class or method depending on the accessing class location and the modifier for the accessed class or class member:
| Modifier | Same class or nested class | Other class inside the same package | Extended Class inside another package | Non-extended inside another package |
|---|---|---|---|---|
| private | yes | no | no | no |
| default (package private) | yes | yes | no | no |
| protected | yes | yes | yes | no |
| public | yes | yes | yes | yes |
Constructors and initializers
A constructor is a special method called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified:
class Foo {
String str;
Foo() { // Constructor with no arguments
// Initialization
}
Foo(String str) { // Constructor with one argument
this.str = str;
}
}
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────